package org.papervision3d.core.animation.track
{
	import flash.errors.IllegalOperationError;
	
	import org.papervision3d.core.animation.keyframe.AbstractKeyFrame;
	import org.papervision3d.core.geom.renderables.Vertex3D;
	import org.papervision3d.core.log.PaperLogger;
	import org.papervision3d.objects.DisplayObject3D;

	/**
	 * The VertexTrack animates the X, Y, or Z property of a Vertex3D.
	 * The keyframe data should be the offset to the original vertex value.
	 * So this data is 'relative', not 'absolute'.
	 * 
	 * This class in mainly used by the DAE class, for COLLADA vertex animation.
	 * 
	 * @author Tim Knip / floorplanner.com
	 */ 
	public class VertexTrack extends AbstractTrack
	{
		public var index :int;
		public var subindex :int;
		public var vertex :Vertex3D;
		
		/**
		 * Constructor.
		 * 
		 * @param	target		The targeted object
		 * @param	index		The index into the targets geometry.vertices array
		 * @param	subindex	Which property of the vertex to target. 0 targets vertex.x, 1 targets vertex.y, 2 targets vertex.z
		 */ 
		public function VertexTrack(target:DisplayObject3D, index:int, subindex:int)
		{
			super(target);
			if(!target.geometry || !target.geometry.vertices || !target.geometry.vertices[index])
			{
				throw new IllegalOperationError("Can't find the targeted vertex!");
			}
			this.index = index;
			this.subindex = subindex;
			this.vertex = target.geometry.vertices[index].clone();
		}
		
		/**
		 * 
		 */ 
		public override function addKeyFrame(keyframe:AbstractKeyFrame):void
		{
			if(!keyframe.data || !(keyframe.data[0] is Number))
			{
				PaperLogger.error("Invalid keyframe data!");
				return;
			}
			super.addKeyFrame(keyframe);
		}
		
		/**
		 * 
		 */ 
		public override function tick(seconds:Number):void
		{	
			if(!target || !target.geometry || !target.geometry.vertices || ! target.geometry.vertices[index])
			{
				return;
			}
			
			super.tick(seconds);
			
			var vert :Vertex3D = target.geometry.vertices[index];
			var u :Number;
			var v :Number;
			
			if(current && next)
			{
				u = current.data[0];
				v = next.data[0];
				
				if(subindex == 0)
				{
					vert.x = vertex.x + (u + alpha * (v - u));
				}
				else if(subindex == 1)
				{
					vert.y = vertex.y + (u + alpha * (v - u));
				}
				else if(subindex == 2)
				{
					vert.z = vertex.z + (u + alpha * (v - u));
				}
			}
			else if(current)
			{
				u = current.data[0];
				if(subindex == 0)
				{
					vert.x = vertex.x + u;
				}
				else if(subindex == 1)
				{
					vert.y = vertex.y + u;
				}
				else
				{
					vert.z = vertex.z + u;
				}
			}
		}
	}
}